#include "anls_core.h"
#define _RELEASE_MODE_ 1
anls_Core::anls_Core(QStatusBar *analysisMessage, QProgressBar *progress, QObject *parent)
    : QObject{parent}
    , m_message(analysisMessage)
    , m_progress(progress)
{
    connect(&this->m_process, QProcess::readyReadStandardOutput, this, on_readoutput);
    connect(&this->m_process, QProcess::readyReadStandardError, this, on_readerror);
    connect(this, anls_Core::analysisFinish, this, this->on_getAnalysisData);
}

anls_Core::~anls_Core()
{
    m_process.close();
}

void anls_Core::analysisImg(const img_Info *info)
{
    m_info = info;
#if _RELEASE_MODE_
    m_progress->setValue(0);
    m_process.setWorkingDirectory(sys_Data::getInstance()->getAnalysisAlgPath());//设置算法工作目录
    m_process.start(
        QString("%1/python.exe %2 %3\n").arg(
            sys_Data::getInstance()->getCondaEnvir(),
            "analysis.py", info->fileName).toStdString().c_str());//启动分析算法
#else //开发时选用
    emit analysisFinish();
#endif
}

void anls_Core::on_getAnalysisData()
{
    //---------------------------------------------------------------
    QFile message(QString("%1/message.temp").arg(sys_Data::getInstance()->getAnalysisAlgPath()));
    message.open(QFile::ReadOnly);
    QStringList list = QString(message.readAll().data()).split('\n');
    double sumv {0.0}, sumlv{0.0};
    for(int i = 1; i < 6; i++) {
        m_data.volume[i] = list[i - 1].toDouble();
        m_data.lesionVolume[i] = list[i + 4].toDouble();
        m_data.lesionDensity[i] = list[i + 9].toDouble();
        sumv += m_data.volume[i];
        sumlv += m_data.lesionVolume[i];
    }
    m_data.volume[0] = sumv;
    m_data.lesionVolume[0] = sumlv;
    m_data.lesionDensity[0] = list[15].toDouble();
    message.close();
    //---------------------------------------------------------------
    readInfection();
    //---------------------------------------------------------------
#if _RELEASE_MODE_
    QFile::remove(QString("%1/message.temp").arg(sys_Data::getInstance()->getAnalysisAlgPath()));
    QFile::remove(QString("%1/Infection.temp").arg(sys_Data::getInstance()->getAnalysisAlgPath()));
#endif
    emit getDataFinish(m_data);
}

void anls_Core::readInfection()
{
    m_data.data = vtkSmartPointer<vtkImageData>::New();
    m_data.data->SetDimensions(256, 256, 192);
    m_data.data->AllocateScalars(VTK_SHORT, 1);
    short *ptr = static_cast<short*>(m_data.data->GetScalarPointer());
    QFile file(QString("%1/Infection.temp").arg(sys_Data::getInstance()->getAnalysisAlgPath()));
    file.open(QFile::ReadOnly);
    for(int z = 0; z < 192; z++) {
        for(int y = 0; y < 256; y++) {
            QStringList list = QString(file.readLine()).split(' ');
            for(int x = 0; x < 256; x++) {
                if(list[x] == "1") {
                    *ptr++ = 1;
                } else {
                    *ptr++ = 0;
                }
            }
        }
    }
    file.close();
    vtkSmartPointer<vtkImageResize> resize = vtkSmartPointer<vtkImageResize>::New();
    vtkSmartPointer<vtkImageInterpolator> interpolator = vtkSmartPointer<vtkImageInterpolator>::New();
    vtkSmartPointer<vtkImageReslice> reslice = vtkSmartPointer<vtkImageReslice>::New();
    vtkSmartPointer<vtkTransform> trsform = vtkSmartPointer<vtkTransform>::New();
    trsform->RotateX(180);//变换到正确位置
    trsform->RotateY(180);
    trsform->Translate(0, 0, 0);
    reslice->SetInputData(m_data.data);
    reslice->SetResliceTransform(trsform);
    reslice->SetAutoCropOutput(1);
    reslice->Update();
    //----------------------------------------------------------------------------------------------------
    interpolator->SetInterpolationModeToLinear();//最邻近插值算法
    resize->SetInputData(reslice->GetOutput());
    resize->SetInterpolator(interpolator);
    resize->SetOutputDimensions(m_info->dim[1], m_info->dim[2], m_info->dim[3]);
    resize->Update();
    m_data.data = resize->GetOutput();
    m_data.data->SetSpacing(m_info->pixdim[1], m_info->pixdim[2], m_info->pixdim[3]);
    m_data.data->SetOrigin(0, 0, 0);
}

void anls_Core::on_readoutput()
{
    QString str = QTextCodec::codecForName("GBK")->toUnicode(this->m_process.readAllStandardOutput());
    if(str.indexOf("[sys]") != -1) {
        m_message->showMessage(str.remove("[sys]"));
        m_progress->setValue(m_progress->value() + 3);
    }
    if(str.indexOf("[cnt]") != -1) {
        int now = str.remove("[cnt]").toUInt() + 1;
        m_message->showMessage(QString("<病灶分割>: 正在进行CT切片推理(%1/192)").arg(now));
        if(now % 3 == 0) {
            m_progress->setValue(m_progress->value() + 1);
        }
    }
    if(str.indexOf("[end]") != -1) {
        m_message->showMessage("正在导入分析结果");
        m_progress->setValue(98);
        m_process.close();
        emit analysisFinish();
    }
}

void anls_Core::on_readerror()
{
    QTextCodec::codecForName("GBK")->toUnicode(this->m_process.readAllStandardError());
}
